#==================================================
#	State Machine Root
#==================================================
#  状态机根节点
#==================================================
# @path: res://addons/function_tree/src/base/layer/custom/StateMachineRoot.gd
# @datetime: 2021-12-18 10:18:29
#==================================================
extends "res://addons/function_tree/src/custom/CustomLayer.gd"


signal state_changed(last_state_name, current_state_name)


var __nodes__ := {}

## 上个执行的 State
var _last_state : Node = null
## 当前执行的 State
var _current_state : Node = null



#==================================================
#   Set/Get
#==================================================
func get_current_state() -> Node:
	return _current_state

func get_last_state() -> Node:
	return _last_state

func get_current_state_name() -> String:
	return _current_state.name

func has_state(state_name: String) -> bool:
	return __nodes__.has(state_name)

func get_state(state_name: String) -> Node:
	return __nodes__[state_name]



#==================================================
#   自定义方法
#==================================================
#(override)
func _init_data():
	._init_data()
	register_to_layer("StateMachineRoot")


#(override)
func _init_finish():
	._init_finish()
	if get_child_count() > 0:
		for child in get_children():
			__nodes__[child.name] = child
		switch_to(get_child(0).name)
	else:
		printerr("没有 State！")


#(override)
func _process_execute(arg0):
	# 一次只执行一个 State 的 process
	if _current_state:
		_current_state.state_process(arg0)


##  切换当前 State
## @state_name  State 名称
## @data=null  启动时的数据
func switch_to(state_name: String, data=null) -> bool:
	if has_state(state_name):
		# 如果存在有正在进行的 State，则停止
		if _current_state != null:
			# 停止当前状态
			_current_state.exit()
		
		_last_state = _current_state
		# 开始启动切换的 State
		var state = get_state(state_name)
		_current_state = state
		_current_state.enter(data)
		if _last_state:
			emit_signal("state_changed", _last_state.name, _current_state.name)
		else:
			emit_signal("state_changed", null, _current_state.name)
		return true
	else:
		printerr("没有这个状态！", state_name)
		return false


